/**
 * 
 */
package com.base.httpClient;

import java.io.IOException;
import java.io.InputStreamReader;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.base.web.controller.BaseController;
import com.model.User;




/**
 * @author leiruiqi
 *
 */
public class httpClientDemo {

	protected final Log log = LogFactory.getLog(BaseController.class);
	
	
	public static JSONObject post(String url,String jsonStr){
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		JSONObject response = null;
		try {
			StringEntity s = new StringEntity(jsonStr);
			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");
			post.setEntity(s);
			
			HttpResponse res = client.execute(post);
			if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				HttpEntity entity = res.getEntity();
				String charset = EntityUtils.getContentCharSet(entity);
				 String rev = EntityUtils.toString(res.getEntity());
				 System.out.println(rev);
				//response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset)));
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return response;
	}
	
	//如何 post json格式的数据，并附加http头，接受返回数据，请看下面的代码：

	
	private void HttpPostData() {  
	try {  
	    HttpClient httpclient = new DefaultHttpClient();  
	    String uri = "http://localhost:8080/test/checkValue.do";  
	    HttpPost httppost = new HttpPost(uri);   
	    //添加http头信息  
	    httppost.addHeader("Authorization", "your token"); //认证token  
	    httppost.addHeader("Content-Type", "application/json");  
	    httppost.addHeader("User-Agent", "imgfornote");  
	    //http post的json数据格式：  {"name": "your name","parentId": "id_of_parent"}  
	    User user = new User();
	  		user.setUserId(12345L);
	  		user.setPassWord("12345");
	  		user.setUserName("ricky");
	  		JSONObject obj = JSONObject.fromObject(user);
	   
	    httppost.setEntity(new StringEntity(obj.toString()));     
	    HttpResponse response;  
	    response = httpclient.execute(httppost);  
	    //检验状态码，如果成功接收数据  
	    int code = response.getStatusLine().getStatusCode();  
	    if (code == 200) {   
	        String rev = EntityUtils.toString(response.getEntity());//返回json格式： {"id": "27JpL~j4vsL0LX00E00005","version": "abc"}         
	       /* obj = JSONOjbect.
	        String id = obj.getString("id");  
	        String version = obj.getString("version");  */
	    }  
	    } catch (ClientProtocolException e) {     
	    } catch (IOException e) {     
	    } catch (Exception e) {   
	    }  
	}  
	//主要用到的类有：org.apache.http.client.HttpClient 、org.apache.http.client.methods.HttpPost 和 org.json.JSONObject
	
	public static void main(String[] args) {
		User user = new User();
  		user.setUserId(12345L);
  		user.setPassWord("12345");
  		user.setUserName("ricky");
  		String obj = JSON.toJSONString(user);
  		String url = "http://localhost:8080/test/checkJson.do";  
  		httpClientDemo.post(url, obj);
	}
}
